package com.hyfrogx.modules.app.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.hyfrogx.common.exception.MyException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * TODO JWT工具类封装
 *
 * @author crazypenguin
 * @version 1.0.0
 * @createdate 2019/1/2
 */
@ConfigurationProperties(prefix = "frogx.jwt")
@Component
public class JwtUtils {
    private Logger logger = LoggerFactory.getLogger(getClass());

    // 读取配置文件的相关属性
    private String secret;
    private long expire;
    private String header;

    /**
     * 生成JWT Token
     *
     * @param userId
     * @return
     */
    public String generateToken(Long userId, String userName) {
        JSONObject json = new JSONObject();
        json.put("userId", userId);
        json.put("userName", userName);
        return generateToken(json);
    }

    /**
     * 生成JWT Token
     *
     * @param json
     * @return
     */
    public String generateToken(JSONObject json) {
        Date nowDate = new Date();
        // 过期时间,这边单位是ms
        Date expireDate = new Date(nowDate.getTime() + expire * 1000);
        if (ObjectUtil.isNull(json) || json.isEmpty()) {
            throw new MyException("token异常");
        }
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(json.toJSONString())
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 生成JWT Token
     *
     * @param subject
     * @return
     */
    public String generateToken(String subject) {
        Date nowDate = new Date();
        // 过期时间,这边单位是ms
        Date expireDate = new Date(nowDate.getTime() + expire * 1000);
        if (StrUtil.isEmpty(subject)) {
            throw new MyException("token异常");
        }
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(subject)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 解析token
     *
     * @param token
     * @return
     */
    public Claims getClaimByToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            logger.error("无效token: ", e);
            return null;
        }
    }

    /**
     * 验证token是否过期
     *
     * @param expiration
     * @return
     */
    public boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    public long getExpire() {
        return expire;
    }

    public void setExpire(long expire) {
        this.expire = expire;
    }

    public String getHeader() {
        return header;
    }

    public void setHeader(String header) {
        this.header = header;
    }
}
